<?php
// $Id: Controller.php 609 2012-12-17 01:23:51Z tomqin@gmail.com $

/**
 * Part of the framework.
 *
 * @package     Library
 * @version     1.0
 * @copyright   Copyright (C) 2010-2012 SupeFun.com Inc.
 * @author      TomQin <tomqin@gmail.com>
 * @license     http://www.supefun.com/license/
 */

class Controller
{

    public $action;

    public $var = array();

    public function setAction($action) {
        $this->action = empty($action)? 'index' : $action;
    }

    //取得 controller / module
    public function __get($name){
        if($name == 'controller')
            return strtolower(substr(get_class($this), 0, -10));
        else if($name == 'module'){
            $o = new ReflectionClass(get_class($this));
            return basename(dirname($o->getFileName()));
        }
    }

    public function setVar($key, $var) {
        $this->var[$key] = $var;
    }

    public function getVar($key) {
        return isset($this->var[$key]) ? $this->var[$key] : null;
    }

    public function defaultAction(){
        echo('It\'s default action.');
    }

    public function beforeAction(){}

    public function afterAction(){}

    public function run(){
        $action = $this->action.'Action';
        $this->beforeAction();
        if(method_exists($this, $action)){
            $this->$action();
        }else{
            $this->defaultAction();
        }
        $this->afterAction();
    }

    public function render($tpl) {
        extract($this->var);
        include $this->tpl($tpl);

        $this->afterAction();
        exit();
    }

    public function tpl($tpl) {
        return BASE_PATH.'source'.DS.'template'.DS.str_replace('.', DS, $tpl).'.tpl.php';
    }

    public function renderJSON(array $arr) {
        echo json_encode($arr);

        $this->afterAction();
        exit();
    }

    //载入控制器
    static public function loadController($folder, $module, $controller){
        $module     = empty($module) ? 'default' : strtolower($module);
        $controller = empty($controller) ? 'main' : strtolower($controller);
        $classname  = ucfirst($controller).'Controller';
        $classname  = "controller.{$folder}.{$module}.{$classname}";
        $class  = Base::import($classname, true);
        if($class)
            return new $class;
        else
            return null;
    }

    //构造器
    public function __construct(){}

    //析构器
    public function __destory(){}
}
